package com.example.teach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teach.entity.Comment;
import com.example.teach.entity.Result;
import com.example.teach.entity.User;
import com.example.teach.mapper.ArticleMapper;
import com.example.teach.mapper.CommentMapper;
import com.example.teach.mapper.UserMapper;
import com.example.teach.service.CommentService;
import com.example.teach.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService{

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result add(Comment comment) {
        comment.setCreateTime(LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES));
        commentMapper.insert(comment);
        articleMapper.addComment(comment.getArticleId());
        return Result.success("评论成功");
    }

    @Override
    public Result delete(Integer contentId, Integer articleId, Integer userId) {
        // 先验证，只能删自己的评论
        Comment comment = commentMapper.selectById(contentId);
        if(!comment.getUserId().equals(userId)){
            return Result.error("你不能删别人的评论");
        }

        if(0 == commentMapper.selectByParentId(contentId)){
            commentMapper.deleteByParentId(contentId);
        }
        commentMapper.deleteById(contentId);
        articleMapper.subComment(articleId);
        return Result.success();
    }

    @Override
    public Result select(Integer articleId) {
        List<Comment> lists = commentMapper.selectList(new QueryWrapper<Comment>().eq("article_id",articleId));
        List<CommentVO> commentVOS = new ArrayList<>();
        for(Comment list : lists){
            CommentVO commentVO = new CommentVO();
            commentVO.setId(list.getId());
            commentVO.setContent(list.getContent());
            commentVO.setArticleId(list.getArticleId());
            commentVO.setUserId(list.getUserId());
            User user = userMapper.selectById(list.getUserId());
            if(null != user){
                commentVO.setUserName(user.getUserName());
            }
            commentVO.setParentId(list.getParentId());
            commentVO.setCreateTime(list.getCreateTime());
            commentVOS.add(commentVO);
        }
        return Result.success(commentVOS);
    }
}
